<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
    status-icon>
    <el-form-item label="用户账号" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="用户密码" prop="password">
      <el-input v-model="ruleForm.password" />
    </el-form-item>
    <el-form-item label="用户角色" prop="objectId">
      <el-select @change="handleChange">
        <el-option :key="item.objectId" v-for="item in roleList" :label="item.name" :value="item.objectId" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> 新增 </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { postRoleList } from '@/api/role'
// import { MainRoutes } from "@/router"
// import { getRoleList } from "@/api/role"
interface RuleForm {
  username: string
  password: string
  objectId: string
  roleName: string
}

interface RoleType {
  name: string
  objectId: string
}

const props = defineProps(['roleList'])
let roleList = reactive<Array<RoleType>>([])
const formSize = ref('default')
// let roleList = reactive<Array<RoleType>>([])
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
  roleName: '',
  objectId: ''
})

roleList = props.roleList

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请填写账号', trigger: 'blur' }
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请设置密码',
      trigger: 'change'
    }
  ],
  objectId: [
    {
      required: true,
      message: '请勾选角色权限',
      trigger: 'change'
    }
  ]
})

const handleChange = (e) => {
  // console.log(props.drawer)
  ruleForm.objectId = e
  let names = roleList.find((a) => a.objectId == e).name
  ruleForm.roleName = names
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!', ruleForm)
      // postRoleListApi(ruleForm)

      postRoleList(ruleForm)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
